﻿using System;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// 加载按钮
    /// </summary>
    public class LoadingButton : Button
    {
        public const float defaultAnimationDuration = 1f;

        public new event Func<Task> onClick;

        private readonly Icon loadingIcon;
        private readonly VisualElement mask;

        private bool loading;

        internal LoadingButton(ElementFactory elementFactory) : base(elementFactory)
        {
            Add(mask = EditorElementUtility.elementFactory.CreateEditorElement(new Color32(0, 0, 0, 66)));
            mask.style.display = DisplayStyle.None;
            mask.StretchToParentSize();
            loadingIcon = EditorElementUtility.elementFactory.CreateIcon(PackageAssets.Icons.refresh, EditorElementUtility.unitySoftWhiteColor);
            loadingIcon.style.SetTransition("rotate", defaultAnimationDuration);
            loadingIcon.style.position = Position.Absolute;
            loadingIcon.style.right = 8f;
            loadingIcon.RegisterCallback<TransitionEndEvent>(_ => loadingIcon.style.SetRotate(loadingIcon.style.rotate.value.angle.value + 360f));
            base.onClick += OnClickCallback;
        }

        private async void OnClickCallback()
        {
            if (onClick == null || loading) return;
            loading = true;
            mask.style.display = DisplayStyle.Flex;
            Add(loadingIcon);
            schedule.Execute(() => loadingIcon.style.SetRotate(360f)).ExecuteLater(10);
            await onClick();
            mask.style.display = DisplayStyle.None;
            loadingIcon.style.SetRotate(0f);
            Remove(loadingIcon);
            loading = false;
        }
    }
}